import java.io.*;
import java.net.*;
import java.util.Date;

public class MyUdpServer {
    public static void main(String[] args) {
        int port = 6666; // 服务端端口
        try (DatagramSocket serverSocket = new DatagramSocket(port)) {
            System.out.println("Time server is running on port " + port);

            byte[] receiveData = new byte[1024];
            byte[] sendData = new byte[1024];

            while (true) {
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                serverSocket.receive(receivePacket); // 接收客户端请求

                // 获取当前时间
                Date now = new Date();
                String currentTime = now.toString();
                System.out.println("Sending time to " + receivePacket.getAddress().getHostAddress() + ":" + receivePacket.getPort());
                sendData = currentTime.getBytes();

                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, receivePacket.getAddress(), receivePacket.getPort());
                serverSocket.send(sendPacket); // 发送当前时间给客户端
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}